/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.websockets;

import com.entities.EventTypeCharts;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.ApplicationScoped;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonArrayBuilder;
import javax.json.JsonObject;
import javax.json.spi.JsonProvider;
import javax.websocket.Session;

/**
 *
 * @author Tuan Long
 */
@ApplicationScoped
public class AdminSessionHandler {

    private int count;
    private final Set<Session> sessions = new HashSet<>();
    private final Set<ChartDataManager> charts = new HashSet<>();
    
    public void addChart(ChartDataManager manager){
        manager.setId(count);
        charts.add(manager);
        count++;
        JsonArray addMessage = createAddMessage(manager);
        sendToAllConnectedSession(addMessage);
    }
        
    void addSession(Session session) {
        sessions.add(session);
        for (ChartDataManager chart : charts) {
            JsonArray message = createAddMessage(chart);
            sentToSession(session, message);
        }
    }

    void removeSession(Session session) {
        sessions.remove(session);
    }

    private JsonArray createAddMessage(ChartDataManager manager) {        
        List<EventTypeCharts> list = manager.getData();
        JsonArrayBuilder builder = Json.createArrayBuilder();
        for (EventTypeCharts etc : list) {
            builder.add(createMessage(etc));
        }                
        JsonArray jsonArray = builder.build();
        return jsonArray;
    }
    private String createMessage(EventTypeCharts ec){
        JsonProvider provider = JsonProvider.provider();
        JsonObject obj = provider.createObjectBuilder()
                .add("index", ec.getId())
                .add("tag", ec.getTag())
                .add("amount", ec.getAmount())
                .build();
        return obj.toString();
    }

    private void sendToAllConnectedSession(JsonArray message) {
        for (Session session : sessions) {
            sentToSession(session,message);
        }
    }

    private void sentToSession(Session session, JsonArray message) {
        try {
            session.getBasicRemote().sendText(message.toString());
        } catch (IOException ex) {
            sessions.remove(session);
            Logger.getLogger(AdminSessionHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
}
